package streaming.api.transform;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 基本转换操作
 */
public class TransformTest1 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStream inputStream = env.readTextFile("D:\\IdeaProjects\\springboot-flink-1\\flinkTutorial\\src\\main\\resources\\sensor.txt");
        //1.map
        //把String 转换成长度输出
        DataStream<Integer> mapStream1 = inputStream.map(new MapFunction<String, Integer>() {
            public Integer map(String s) throws Exception {
                return s.length();
            }
        });
        mapStream1.print("map");
        //2.flatmap
        //把String按逗号(,)区分字段,输出二元组
        DataStream flatMapStream1 = inputStream.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>(){
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = s.split(",");
                for (String word: words) {
                    collector.collect(new Tuple2<String, Integer>(word, 1));
                }
            }
        });
        flatMapStream1.print("flatmap");
        //3.filter
        //刷选sensor_1开头的id对应的数据
        DataStream<Integer> filterStream1 = inputStream.filter(new FilterFunction<String>(){
            public boolean filter(String s) throws Exception {
                return s.startsWith("sensor_a");
            }
        });

        filterStream1.print("filter");
        env.execute();
    }
}
